﻿using System;
using System.IO;
using System.Web;
using log4net;

namespace RIBA.Web
{
	public class DllHandler : IHttpHandler
	{
		private static readonly ILog _log = LogManager.GetLogger(typeof(DllHandler));

		public void ProcessRequest(HttpContext context)
		{
			try
			{
				_log.DebugFormat("ProcessRequest");

				context.Response.Clear();

				var dllName = context.Request.Params["dll"];

				//User has access rights for selected DLL
				if (dllName == "Admin" && context.User.IsInRole("Admin"))
				{
					var dllPathVirtual = string.Format("~/ClientBin/secure/{0}.dll", dllName);
					var dllPathPhysical = context.Server.MapPath(dllPathVirtual);
					var fileStream = new FileStream(dllPathPhysical, FileMode.Open);
					var binaryReader = new BinaryReader(fileStream);
					var buffer = binaryReader.ReadBytes((int)fileStream.Length);
					binaryReader.Close();

					context.Response.ContentType = "application/octet-stream";
					context.Response.BinaryWrite(buffer);

					return;
				}

				//DLL not available or no access rights
				context.Response.ContentType = "text/plain";
				context.Response.Write("Not allowed");
			}
			catch (Exception ex)
			{
				_log.Fatal(string.Format("Error in ProcessRequest"), ex);
			}
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}